// 上传至oss的封装文件
import { ElMessage } from 'element-plus'
import { getOSS, getOSSCallBack, getSignApi } from '../components/Api/Upload'
// let basePath  = 'www.yourapi.com' // 你的服务器接口域名
/**
 * @description: 文件附件上传
 * file： 文件raw对象
 * successCallback： 成功的回调函数
 * errCallBack： 错误的回调函数
 * progressCallback： 上传进度的回调函数
 * dir: 上传阿里云目标文件夹 eg:图片image，视频video等
 */
// 随机生成文件名
const random_string = (len?: any) => {
    len = len || 32
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = chars.length
    var pwd = ''
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
}
// 获取文件信息
const getSuffix = (fileName: any) => {
    var pos = fileName.lastIndexOf('.')
    var suffix = ''
    if (pos !== -1) {
        suffix = fileName.substring(pos)
    }
    return suffix
}
const upload = async (file: any, type: string, successCallback = new Function(), errCallBack = new Function(), progressCallback = new Function()) => {
    console.log(file)
    let fileName = getSuffix(file.name)
    const res: any = await getSignApi({ dir: type })
    // if (res.code !== 1) {
    //     return ElMessage({
    //         type: 'error',
    //         message: res.message
    //     })
    // }
    // 拿到签名信息后，组装表单数据，作参考，具体的字段找后台要
    let obj = res.data
    let config: any = {}
    config.host = obj['host']
    config.policyBase64 = obj['policy']
    config.accessid = obj['accessid']
    config.signature = obj['signature']
    config.expire = parseInt(obj['expire'])
    config.callbackbody = obj['callback']
    config.dir = obj['dir']

    let fd = new FormData()
    const key = config.dir + random_string() + fileName
    console.log(key)
    fd.append('key', key)
    fd.append('name', file.name)
    fd.append('x-oss-meta-fullname', fileName)
    fd.append('OSSAccessKeyId', config.accessid)
    fd.append('policy', config.policyBase64)
    fd.append('signature', config.signature)
    fd.append('success_action_status', '200')
    fd.append('file', file)
    // console.log(config.host.indexOf('http:') > -1,"PPPPPPPPPP")
    // if (config.host.indexOf('http:') > -1) {
    //     var protocol = window.location.protocol || 'http:'
    //     var subUrl = config.host.substring(5, config.host.length)
    //     config.host = protocol + subUrl
    // }

    // 数据组装完成后，发送上传请求到阿里云oss
    var fig: any = {
        onUploadProgress: (progressEvent: any) => {
            var complete =
                ((progressEvent.loaded / progressEvent.total) * 100) | 0
            // console.log(complete)
            if (complete < 100) {
                // this.percentageNum = complete
                progressCallback({
                    percent: complete
                })
            }
            // complete为上传时的进度 0-100
        }
    }
    // 拿到结果后，做其他操作
    const data: any = await getOSS(config.host, fd, fig)
    console.log(data)
    if (data.status === 200) {
        // this.percentageNum = 100
        // this.getAliOss(key)
        // // 回调
        // const params = {
        //     dir: key
        // }
        // const res2: any = await getOSSCallBack(params)
        // if (res2.code !== 1) {
        //     return ElMessage({
        //         type: 'error',
        //         message: res2.msg
        //     })
        // }
        // successCallback({
        //     inch: res2.data.content_length,
        //     dir: key,
        //     size: file.size,
        //     name: file.name.split('.')[0]
        // })
        successCallback({
            inch: config.host + '/' + key,
            dir: key,
            size: file.size,
            name: file.name.split('.')[0]
        })
    } else {
        errCallBack(123)
        // this.fileList = []
    }
}
export default upload
